import requests
import parsel
from lxml import etree



url = 'https://www.huya.com/g/4079'
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36'
}
resp = requests.get(url=url, headers=headers)

et = etree.HTML(resp.text)
data_list = et.xpath('//*[@id="js-live-list"]/li')

for item in data_list:
    # item = parsel.Selector(item)
    img_url = item.xpath('./a[1]/img/@data-original')
    name = item.xpath('./span/span[1]/i/text()')
    # print(name, img_url)
    img_url = img_url[0].split('?')[0]

    img_resp = requests.get(url=img_url, headers=headers).content

    # 保存数据
    with open(f'img/{name[0]}.jpg', mode='wb') as f:
        f.write(img_resp)
    print(f'{name[0]}保存成功！')

# selector = parsel.Selector(resp.text)
# data_list = selector.css('.box-live-card-list .clearfix .game-live-item').getall()

# img_url_list = selector.xpath('//li[@class="game-live-item"]/a[1]/img/@data-original').getall()
# name_list = selector.xpath('//li[@class="game-live-item"]//span/i/@title').getall()


# data_list = []
#
# for img_url, name in zip(img_url_list, name_list):
#     data_list.append(name)
#     data_list.append(img_url)
#
# url_1 = data_list[1:len(data_list):2]

# for item in data_list:
#     print(item)
